const qcloud = require('../../vendor/qcloud-weapp-client-sdk/index.js')
const config = require('../../config.js')
const qiniuUploader = require("../../qiniu/qiniuUploader.js")
const utils = require('../../utils.js')
//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    musicState: false,
    play: false,
    playProcess: false,
    curindex: 0,
    recorderManager: '',
    src: '',
    qiniuToken: '',
    ciId: '',
    progress: '0',
    domain: '',
    timeState: false,
    i: 0
  },

  // tab切换
  switchClock(e) {
    this.setData({
      curindex: e.currentTarget.dataset.index
    })


    this.setData({
      curDate: this.data.editData[String(this.data.curindex)] || {}
    })

  },

  // 开始录音
  playFn() {
    this.recorderManager = wx.getRecorderManager();


    this.setData({
      i: 0
    })

    this.recorderManager.start({
      duration: 60000,
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 96000,
      format: 'mp3'
    });


    this.recorderManager.onError(() => {
      this.tip("录音失败！")
    });

    this.recorderManager.onStop((res) => {

      this.setData({
        src: res.tempFilePath
      })

      this.tip("录音完成！")
    });

    if (!!this.data.timeState) {
      return;
    }

    this.setData({
      timeState: true
    })


    this.setData({
      play: true
    })

    // let i = 0
    this.times = setInterval(() => {

      this.setData({
        i: this.data.i + 1
      })

      this.setData({
        progress: Math.ceil(this.data.i / 60 * 100)
      })

      if (this.data.i >= 60 ) {
        this.cutOff()

        clearTimeout(this.times)
      }
    }, 1000)

    this.times
  },

  //结束录制
  cutOff() {
    this.setData({
      timeState: false
    })

    this.setData({
      play: false
    })

    this.setData({
      playProcess: true
    })

    this.setData({
      progress: 0
    })

  },

  // 暂停音频
  pauseFn() {
    this.recorderManager.stop()

    this.cutOff()
    clearTimeout(this.times)
  },

  // 读取音频进度
  onFrameRecorded() {
    this.data.recorderManager.onFrameRecorded((res) => {
      const { frameBuffer } = res
    })
  },

  // 播放音频
  playRecord: function () {
    var that = this;
    var src = this.data.src;

    if (src == '') {
      this.tip("请先录音！")
      return;
    }

    this.innerAudioContext = wx.createInnerAudioContext();

    this.innerAudioContext.onError((res) => {
      this.tip("播放录音失败！")
    })

    this.innerAudioContext.onEnded((res) => {
      this.setData({
        musicState: false
      })
    })

    this.innerAudioContext.src = this.data.src;
    this.innerAudioContext.play()

    this.setData({
      musicState: true
    })
  },

  stopRecord() {
    this.innerAudioContext.pause()
    this.setData({
      musicState: false
    })
  },
  /** 
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    app.globalData.clockRouter = true
    
    var that = this;
    this.recorderManager = wx.getRecorderManager();
    this.recorderManager.onError(function () {
      that.tip("录音失败！")
    });
    this.recorderManager.onStop(function (res) {
      that.setData({
        src: res.tempFilePath
      })

      that.tip("录音完成！")
    });


    this.innerAudioContext = wx.createInnerAudioContext();

    this.innerAudioContext.onError((res) => {
      that.tip("播放录音失败！")
    })

    this.innerAudioContext.onEnded((res) => {
      this.setData({
        musicState: true
      })
    })

    this.setData({
      ciId: options.ciid
    })

    if (options.cpcId) {
      this.setData({
        cpcId: options.cpcId
      })

      this.getobtainCardDetail(this.data.cpcId)
    }

  },

  // 获取打卡详情
  getobtainCardDetail(id) {
    utils.ajaxFn({
      url: config.service.obtainCardDetail,
      body: { 'cpcId': id },
      callback: (data) => {
        let obj = data.cardDTO
        let objJson = {}
        let key
        obj.contents.forEach((value, index) => {

          if (obj.type == 0 && value.type == 0) {
            key = 0
          } else if (obj.type == 0 && value.type == 1) {
            key = 1
          } else {
            key = 2
          }

          objJson[key] = value
        })

        this.setData({
          editData: objJson
        })

        this.setData({
          curindex: key
        })


        this.setData({
          curDate: this.data.editData[String(this.data.curindex)] || {}
        })

        this.setData({
          src: this.data.curDate.content
        })

        if(this.data.src != '') {
          this.data.frequency = this.data.src
          this.cutOff()
        }
      }
    })
  },

  // 初始化为空
  anewTranscribe() {
    this.setData({
      play: false
    })

    this.setData({
      playProcess: false
    })

    this.innerAudioContext = null
  },

  // 提交音频
  uploadfrequency (image) {

    if (!this.data.qiniuToken && this.data.src != '') {
      //获取七牛token
      this.getobtainPictureUploadToken().then((v) => {
        this.qiniuUploaderFn()
      })
    } else {
      this.tip("请录制音频或网络错误")
    }

    this.qiniuUploaderFn()
  },

  qiniuUploaderFn() {
    // 交给七牛上传
    qiniuUploader.upload(this.data.src, (res) => {
      // 每个文件上传成功后,处理相关的事情
      // 其中 info 是文件上传成功后，服务端返回的json，形式如
      this.data.frequency = res.imageURL;

      let obj = { 'type': 1, 'content': this.data.frequency, 'duration': this.data.i, cccId: this.data.cccId }
      
      this.getpunchCard({
        contentsJn: `[${JSON.stringify(obj)}]`,
        type: 0,
        punchDate: this.curTime(),
        cpcId: this.data.cpcId
      })


    }, (error) => {
      wx.showModal({
        title: '提示',
        content: '上传失败',
        showCancel: false
      })
    },
      {
        region: 'ECN',
        domain: this.data.domain, // // bucket 域名，下载资源时用到。如果设置，会在 success 
        uptoken: this.data.qiniuToken, // 由其他程序生成七牛 uptoken

      })

  },
  // 获取token
  getobtainPictureUploadToken() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: config.service.obtainPictureUploadToken,
        method: "POST",
        success: (data) => {
          this.setData({ domain: data.data.domain });
          this.setData({ qiniuToken: data.data.upToken });
          resolve()
        }
      })
    })
  },

  tip (msg) {
    wx.showModal({
      title: '提示',
      content: msg,
      showCancel: false
    })
  },

  getpunchCard(obj){
    utils.ajaxFn({
      url: config.service.modifyCard,
      body: obj,
      callback: (data) => {
        wx.showToast({
          title: '修改打卡成功！',
          duration: 2000
        })

        setTimeout(() => {
          // wx.navigateTo({
          //   url: '/pages/index/index'
          // })
          wx.navigateBack({
            delta:100
          })

        }, 1000)
        // setTimeout(() => {
        //   wx.navigateTo({
        //     url: '/pages/index/index'
        //   })

          
        // }, 2000)
      }
    })
  },

  // 文字打卡输入内容
  bindFormSubmit(e) {
    let obj = { 'type': 0, 'content': e.detail.value.textarea, cccId: this.data.cccId }
    this.getpunchCard({
      contentsJn: `[${JSON.stringify(obj)}]`,
      type: e.currentTarget.dataset.type,
      punchDate: this.curTime(),
      cpcId: this.data.cpcId
    })
  },

  // 不零操作数据
  zeroize(value) {
    return value < 9 ? `0${value}` : value
  },

  curTime() {
    var times = new Date()

    return `${times.getFullYear()}-${this.zeroize(times.getMonth() + 1)}
            -${this.zeroize(times.getDate())} ${this.zeroize(times.getHours())}:00:00`
  }
})